/*
 * Logger.cpp
 *
 *   Created on: 2010-3-29     
 *  Description: 
 *    Copyright: 2010 @ ICT Li Heyuan
 */

#include "../../include/util/Logger.h"
#include "../../include/util/Util.h"

#include <cstdarg>
#include <stdexcept>

#include <sys/timeb.h>

Logger::Logger(const string &file)
{
	//检查日志名
	if (file.empty())
	{
		_file = "untitle.log";
	}
	else
	{
		_file = file;
	}

	_isLog = true;

	//打开日志文件
	_out.open(_file.c_str(), std::ios_base::out | std::ios_base::app);
	if (_out.fail())
	{
		throw std::runtime_error("can't open logfile " + file);
	}

	//初始化锁
	pthread_mutex_init(&_mutex_log, 0);

}

Logger::~Logger()
{
	_out.close();
	pthread_mutex_destroy(&_mutex_log);
}

void Logger::log(const int& type, const string &format, va_list args)
{
	if (!_isLog)
	{
		return;
	}

	//关键区 开始
	pthread_mutex_lock(&_mutex_log);

	//构造字符串
	char *buf = new char[LOG_MSG_MAX + 1];
	vsnprintf(buf, LOG_MSG_MAX, format.c_str(), args);

	_out << Util::getFormatTime() << " ";//输出时间

	//输出type
	switch (type)
	{
	case DEBUG:
		_out << "[DEBUG]";
		break;
	case INFO:
		_out << "[INFO]";
		break;
	case ERROR:
		_out << "[ERROR]";
		break;
	}
	//输出name
	//	out << "[" << _name << "]" << " ";
	//
	//输出日志信息
	_out << " " << buf << std::endl;
	delete[] buf;

	//关键区 结束
	pthread_mutex_unlock(&_mutex_log);
}

void Logger::log(const int& type, const string &format, ...)
{
	if (!_isLog)
	{
		return;
	}

	va_list args;
	va_start( args, format);
	log(type, format, args);
	va_end(args);
}

void Logger::error(const string &format, ...)
{
	if (!_isLog)
	{
		return;
	}

	va_list args;
	va_start( args, format);
	log(ERROR, format, args);
	va_end(args);
}

void Logger::info(const string &format, ...)
{
	if (!_isLog)
	{
		return;
	}

	va_list args;
	va_start( args, format);
	log(INFO, format, args);
	va_end(args);
}

void Logger::debug(const string &format, ...)
{
	if (!_isLog)
	{
		return;
	}

	va_list args;
	va_start( args, format);
	log(DEBUG, format, args);
	va_end(args);
}

void Logger::setIsLog(bool log)
{
	_isLog = log;
}
